// utils/Draw.js

/**
 * 绘制圆形
 * @param {Object} map - 地图实例
 * @param {Array} center - 圆心的经纬度坐标 [lng, lat]
 * @param {number} radius - 圆的半径（单位：米）
 * @param {string} layerId - 图层的唯一ID
 * @param {string} color - 圆的填充颜色
 * @param {number} opacity - 圆的透明度
 */
export const drawCircle = (
  map,
  center,
  radius,
  layerId,
  color = "#FF0000",
  opacity = 0.5
) => {
  const degrees = radius / 111320 // 1度大约等于111320米
  const circleGeoJSON = turf.circle(center, degrees, {
    steps: 64,
    units: "degrees",
  })

  if (map.getSource(layerId)) {
    map.getSource(layerId).setData(circleGeoJSON)
  } else {
    map.addSource(layerId, {
      type: "geojson",
      data: circleGeoJSON,
    })

    map.addLayer({
      id: layerId,
      type: "fill",
      source: layerId,
      paint: {
        "fill-color": color,
        "fill-opacity": opacity,
      },
    })
  }
}

/**
 * 绘制扇形  -- 角度设置正确可以直接绘制圆
 * @param {Object} map - 地图实例
 * @param {Array} center - 扇形的中心点经纬度坐标 [lng, lat]
 * @param {number} radius - 扇形的半径（单位：米）
 * @param {number} bearing - 扇形的起始角度（单位：度）
 * @param {number} angle - 扇形的角度（单位：度）
 * @param {string} layerId - 图层的唯一ID
 * @param {string} color - 扇形的填充颜色
 * @param {number} opacity - 扇形的透明度
 */
export const drawSector = (
  map,
  center,
  radius,
  bearing,
  angle,
  layerId,
  color = "#00FF00",
  opacity = 0.5
) => {
  const degrees = radius / 111320 // 1度大约等于111320米
  const sectorGeoJSON = turf.sector(center, degrees, bearing, angle, {
    steps: 64,
    units: "degrees",
  })

  if (map.getSource(layerId)) {
    map.getSource(layerId).setData(sectorGeoJSON)
  } else {
    map.addSource(layerId, {
      type: "geojson",
      data: sectorGeoJSON,
    })

    map.addLayer({
      id: layerId,
      type: "fill",
      source: layerId,
      paint: {
        "fill-color": color,
        "fill-opacity": opacity,
      },
    })
  }
}

/**
 * 移除图层
 * @param {Object} map
 * @param {string} layerId - 图层的唯一ID
 */
export const removeLayer = (map, layerId) => {
  if (map.getLayer(layerId)) {
    map.removeLayer(layerId)
  }
  if (map.getSource(layerId)) {
    map.removeSource(layerId)
  }
}
